import { loginApi, getUserDetail } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 存储token到state
    setUserToken(state, token) {
      state.token = token
      setToken(token)
    },
    // 删除token
    delUserToken(state) {
      state.token = ''
      removeToken()
    },
    // 获取用户基本资料
    setUserInfo(state, data) {
      console.log(data)
      state.userInfo = data.userinfo
    },
    // 删除用户基本资料
    delUserInfo(state) {
      state.userInfo = {}
    }

  },
  actions: {
    // 调用登录接口
    async setLoginToken(ctx, data) {
      const { token } = await loginApi(data)
      console.log(token)
      ctx.commit('setUserToken', token)
    },
    // 调用获取用户资料
    async getUserInfo(ctx) {
      const res = await getUserDetail()
      console.log(res)
      ctx.commit('setUserInfo', res)
    },
    // 退出登录
    logout(ctx) {
      ctx.commit('delUserToken')
      ctx.commit('delUserInfo')
    }
  }
}
